package com.spring.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Base64;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Created by sunhellc on 16/6/30.
 */
public class DatetimeUtil {

    /**
     * 获取系统时间
     *
     * @param dateFormatStr 日期格式字符串 如： yyyy-MM-dd
     * @return 系统时间字符串
     */
    public static String getSysDate(String dateFormatStr) {
        String systemDate = "";
        if (dateFormatStr != null) {
            Calendar date = Calendar.getInstance();
            SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatStr);
            systemDate = dateFormat.format(date.getTime()); // 系统时间
        }
        return systemDate;
    }

    /**
     * string类型时间转换为date
     *
     * @param strDate
     * @return
     */
    public static String strToDateLong(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return  dateToString(strtodate) ;
    }



    public static String dateToString(Date data) {
        return new SimpleDateFormat("HH:mm:ss").format(data);
    }
    /**
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }

    public static String getSysDate1(String dateFormatStr) {
        String systemDate = "";
        if (dateFormatStr != null) {
            Calendar date = Calendar.getInstance();
            int month = date.get(Calendar.MONTH);

            date.set(Calendar.MONTH, month - 1);
            SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatStr);
            systemDate = dateFormat.format(date.getTime()); // 系统时间
        }
        return systemDate;
    }

    /**
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    /**
     * 通过Base32将Bitmap转换成Base64字符串
     *
     * @param bit
     * @return
     */
    public static String Bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    /**
     * 将时间转化成分
     * 时间格式: yyyy-MM-dd HH:mm:ss
     *
     * @param time
     * @return
     */
    public static int timeStrToSecond(String time) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            int second = format.parse(time).getHours();
            int Minutes = format.parse(time).getMinutes();
            return (second * 60) + Minutes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 2个时间相差多少分钟
     *
     * @param Time
     * @return
     */
    public static long Getminutes(String TimeOne, String TimeTwo) {
        long minutes = 1;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar date = Calendar.getInstance();
        String systemDate = df.format(date.getTime()); // 系统时间
        try {
            long d1 = df.parse(TimeOne).getTime();
            long d2 = df.parse(TimeTwo).getTime();
            long diff = d1 - d2;//这样得到的差值是微秒级别  
//            long days = diff / (1000 * 60 * 60 * 24);
//            long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
            minutes = diff / (1000 * 60);
//            System.out.println("" + days + "天" + hours + "小时" + minutes + "分");
        } catch (Exception e) {
        }
        return minutes;
    }

    /**
     * 毫秒转日期
     *
     * @param dateTime
     * @return
     */
    public static String getFormatedDateTime(long dateTime) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sDateFormat.format(new Date(dateTime + 0));
    }

    public static String getSysDate2(String dateFormatStr) {
        String systemDate = "";
        if (dateFormatStr != null) {
            Calendar date = Calendar.getInstance();
            int day = date.get(Calendar.DAY_OF_MONTH);

            date.set(Calendar.DAY_OF_MONTH, day + 1);
            SimpleDateFormat dateFormat = new SimpleDateFormat(dateFormatStr);
            systemDate = dateFormat.format(date.getTime()); // 系统时间
        }
        return systemDate;
    }

    /**
     * 将毫秒转化成固定格式的时间
     * 时间格式: yyyy-MM-dd HH:mm:ss
     *
     * @param millisecond
     * @return
     */
    public static String getDateTimeFromMillisecond(Long millisecond) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(millisecond);
        String dateStr = simpleDateFormat.format(date);
        return dateStr;
    }

    /**
     * 将时间转化成毫秒
     * 时间格式: yyyy-MM-dd HH:mm:ss
     *
     * @param time
     * @return
     */
    public static Long TimeStrToSecond(String time) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Long second = format.parse(time).getTime();
            return second;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return -1l;
    }

    public static String gethour(String hour) {
        String dateStr = "";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
           // 用parse方法，可能会异常，所以要try-catch
            Date date = format.parse(hour);
            // 获取日期实例
            Calendar calendar = Calendar.getInstance();
            // 将日历设置为指定的时间
            calendar.setTime(date);
            // 获取年
            int year = calendar.get(Calendar.YEAR);
            // 这里要注意，月份是从0开始。
            int month = calendar.get(Calendar.MONTH);
            // 获取天
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            if (minute < 10) {
                dateStr = HOUR + ":" + "0" + minute;
            } else if (minute == 0) {
                dateStr = HOUR + ":" + "00";
            } else {
                dateStr = HOUR + ":" + minute;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateStr;
    }
    public static String getTiem(String hour) {
        String dateStr = "";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {

            // 用parse方法，可能会异常，所以要try-catch
            Date date = format.parse(hour);
            // 获取日期实例
            Calendar calendar = Calendar.getInstance();
            // 将日历设置为指定的时间
            calendar.setTime(date);
            // 获取年
            int year = calendar.get(Calendar.YEAR);
            // 这里要注意，月份是从0开始。
            int month = calendar.get(Calendar.MONTH);
            // 获取天
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            int second = calendar.get(Calendar.SECOND);
            Log.d("TAG","second:"+second);
            if (minute < 10&&second<10) {
                dateStr = HOUR + ":" + "0" + minute+":0"+second;
            } else if (minute < 10) {
                dateStr = HOUR + ":" + "0" + minute+":"+second;
            } else  if (second<10){
                dateStr = HOUR + ":" +  minute+":"+"0"+second;
            }else  if (minute==0&&second==0){
                dateStr = HOUR + ":" + "00:00" ;
            }else  if (minute==0){
                dateStr = HOUR + ":" + "00:"+second ;
            }else if (second==0){
                dateStr = HOUR + ":" + minute+"00" ;
            }else  {
                dateStr = HOUR + ":" + minute+":"+second ;
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateStr;
    }

    /**
     * 提供精确的乘法运算。
     *
     * @param v1 被乘数
     * @param v2 乘数
     * @return 两个参数的积
     */
    public static double mul(double v1, double v2) {
        BigDecimal b1 = new BigDecimal(Double.toString(v1));
        BigDecimal b2 = new BigDecimal(Double.toString(v2));
        return b1.multiply(b2).doubleValue();
    }

    public static int getYear() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat yearSdf = new SimpleDateFormat("yyyy");
        String yearString = yearSdf.format(calendar.getTime());
        return Integer.parseInt(yearString);
    }

    public static String getMonth() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat monthSdf = new SimpleDateFormat("MM");
        String monthString = monthSdf.format(calendar.getTime());
        return monthString;
    }

    public static String getDate() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateSdf = new SimpleDateFormat("dd");
        String dateString = dateSdf.format(calendar.getTime());
        return dateString;
    }

    /**
     * 获取星期几
     *
     * @return
     */
    public static String getWhere() {
        String wher = "";
        Calendar calendar = Calendar.getInstance();
        String week = String.valueOf(calendar.get(Calendar.DAY_OF_WEEK));
        if ("1".equals(week)) {
            wher = "天";
        } else if ("2".equals(week)) {
            wher = "一";
        } else if ("3".equals(week)) {
            wher = "二";
        } else if ("4".equals(week)) {
            wher = "三";
        } else if ("5".equals(week)) {
            wher = "四";
        } else if ("6".equals(week)) {
            wher = "五";
        } else if ("7".equals(week)) {
            wher = "六";
        }


        return wher;
    }

    public static int getDayOfMonth() {
        Calendar aCalendar = Calendar.getInstance(Locale.CHINA);
        int day = aCalendar.getActualMaximum(Calendar.DATE);
        return day;
    }

    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
        } else {
            NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /*
 * 获取当前程序的版本号
 */
    public static int getVersionName(Context context) throws Exception {
        //获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        //getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        return packInfo.versionCode;
    }

    public static boolean requestDownload(URL url, String filename) {
        try {
            // 打开连接
            URLConnection con = url.openConnection();
            //获得文件的长度
            int contentLength = con.getContentLength();
            System.out.println("长度 :" + contentLength);
            // 输入流
            InputStream is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            OutputStream os = new FileOutputStream(filename);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            os.close();
            is.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 时间的区域
     *
     * @param start
     * @param end
     * @returnstart
     */
    public static boolean TimeCompare(String current, String start, String end) {
        String[] dds = start.split(":");
        String[] dds1 = end.split(":");
        String[] dds3 = current.split(":");
        int second = Integer.parseInt(dds[1]) + (Integer.parseInt(dds[0]) * 60);   //分钟
        int second1 = Integer.parseInt(dds1[1]) + (Integer.parseInt(dds1[0]) * 60);
        int second3 = Integer.parseInt(dds3[1]) + (Integer.parseInt(dds3[0]) * 60);


        if (second3 >= second && second3 <= second1) {
            return true;
        }

        return false;
    }

    public static int Size(String start, String end) {
        int tiem = 0;
        String[] dds = start.split(":");
        String[] dds1 = end.split(":");

        int second = Integer.parseInt(dds[1]) + (Integer.parseInt(dds[0]) * 60);   //分钟
        int second1 = Integer.parseInt(dds1[1]) + (Integer.parseInt(dds1[0]) * 60);
        tiem = second1 - second;
        return tiem;
    }
}